<template>
  <div>
    <el-card
      shadow="never"
      :body-style="{ padding: '0px' }"
      :current-page="pageNo"
      :page-size="pageSize"
      :total="totalCount"
      @current-change="handleCurrentChange"
    >
      <el-form class="p-4" inline :model="dataForm">
        <el-form-item>
          <el-input
            v-model="userName"
            clearable
            :placeholder="$t('common.customer_name')"
            @clear="clearContractName"
            ref="name"
            @focus="getKeyId($event)"
          />
        </el-form-item>
        <el-form-item>
          <el-date-picker
            v-model="selectTime"
            type="monthrange"
            unlink-panels
            format="YYYY-MM"
            value-format="yyyyMM"
            range-separator="-"
            :start-placeholder="$t('common.start_time')"
            :end-placeholder="$t('common.end_time')"
            :picker-options="pickerOptions"
          />
        </el-form-item>
        <el-form-item>
          <el-select v-model="event" clearable :placeholder="$t('modules.report.event')">
            <el-option
              v-for="item in eventTypeList"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-select v-model="status" clearable :placeholder="$t('common.status')">
            <el-option
              v-for="item in logStatusList"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" class="w-8" @click="getLogList">
            <svg-icon icon-class="search" />
          </el-button>
        </el-form-item>
        <!-- <el-button type="primary" size="small" style="margin:0px" @click="() => $router.push('/add/contract')"><i class="el-icon-plus" size="small" /></el-button> -->
      </el-form>
      <el-table :data="logList" v-loading="loading" stripe>
        <el-table-column :label="$t('common.customer_name')" prop="customerName">
          <template v-slot="scope">
            <div>
              <el-tooltip v-if="scope.row.customerName != '-'" placement="top-start">
                <template #content>
                  <div style="max-width: 300px; line-height: 160%">
                    <span
                      >{{ $t("common.customer_type") }}:
                      {{ scope.row.characterCode }} (ID: {{ scope.row.keyId }})</span
                    ><br /></div
                ></template>
                <div>
                  {{ scope.row.customerName }}
                </div>
              </el-tooltip>
              <div v-else>{{ scope.row.customerName }}</div>
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="month" :label="$t('common.month')" />
        <el-table-column prop="eventTypeDes" :label="$t('modules.report.event')">
          <template v-slot="scope">
            <span>{{
              $t("modules.report.event_type[" + scope.row.eventTypeDes + "].label")
            }}</span>
          </template>
        </el-table-column>
        <el-table-column :label="$t('modules.report.exception')">
          <template v-slot="scope">
            <div>
              <el-tooltip placement="top-start">
                <template #content>
                  <div style="max-width: 400px; line-height: 160%">
                    <span>{{ scope.row.exceptionDesc }}</span>
                  </div></template
                >
                <div>
                  {{ scope.row.exceptionDescSimple }}
                </div>
              </el-tooltip>
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="dealRemark" :label="$t('modules.report.remark')" />
        <el-table-column
          :label="$t('common.status')"
          prop="status"
          style="background-color: pink"
        >
          <template v-slot="scope">
            <div class="montyly-resource-settlement-tooltip">
              <el-tooltip
                v-if="scope.row.status === 0 || scope.row.status === 2"
                placement="top-start"
              >
                <template #content>
                  <div style="max-width: 300px; line-height: 160%">
                    <span
                      >{{ $t("modules.report.update_time") }}:
                      {{ scope.row.updTime }}</span
                    ><br />
                    <span
                      >{{ $t("modules.report.update_person") }}:
                      {{ scope.row.updUsername }}</span
                    >
                  </div></template
                >
                <div>
                  <el-tag
                    size="small"
                    :type="
                      scope.row.status === 0
                        ? 'success'
                        : scope.row.status == 1
                        ? 'warning'
                        : 'danger'
                    "
                    disable-transitions
                  >
                    {{
                      scope.row.status === 0
                        ? $t("modules.report.log_status_list.dealt")
                        : scope.row.status == 1
                        ? $t("modules.report.log_status_list.waiting")
                        : $t("modules.report.log_status_list.ignore")
                    }}
                  </el-tag>
                </div>
              </el-tooltip>
            </div>
            <el-tag
              v-if="scope.row.status === 1"
              size="small"
              :type="
                scope.row.status === 0
                  ? 'success'
                  : scope.row.status == 1
                  ? 'warning'
                  : 'danger'
              "
              disable-transitions
            >
              {{
                scope.row.status === 0
                  ? $t("modules.report.log_status_list.dealt")
                  : scope.row.status == 1
                  ? $t("modules.report.log_status_list.waiting")
                  : $t("modules.report.log_status_list.ignore")
              }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column :label="$t('common.create_time')" prop="creDate">
          <template v-slot="scope">
            <div>
              <el-tooltip placement="top-start">
                <template #content>
                  <div style="max-width: 300px; line-height: 160%">
                    <span>{{ scope.row.creTime }}</span
                    ><br /></div
                ></template>
                <div>
                  {{ scope.row.creDate }}
                </div>
              </el-tooltip>
            </div>
          </template>
        </el-table-column>
        <el-table-column width="75px">
          <template v-slot="scope">
            <el-button
              v-permission="{ permission: '10401004.MANAGE' }"
              text
              class="w-8"
              @click="editStatus(scope.row)"
              ><svg-icon icon-class="Edit"
            /></el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>
    <!-- 获取用户名称的对话框 -->
    <el-dialog
      :title="$t('common.customer_name')"
      v-model="getUserNameVisible"
      width="65%"
      @close="userNameDialogClose"
    >
      <el-card
        shadow="never"
        :body-style="{ padding: '0px' }"
        :current-page="namePageNo"
        :page-size="namePageSize"
        :total="nameTotalCount"
        @current-change="handleNameCurrentChange"
      >
        <div style="margin: 10px">
          <el-input
            v-model="condition"
            clearable
            size="small"
            class="inputModify"
            :placeholder="$t('common.name_id')"
            style="width: 500px; margin-right: 10px"
            @clear="clearSearchName"
            ref="name"
          />
          <el-button
            type="primary"
            class="align-middle p-1.5"
            size="small"
            @click="getKeyId($event)"
          >
            <svg-icon icon-class="search" class="text-lg" />
          </el-button>
          <div style="float: right">
            <el-button
              style="border: none; margin-right: 10px"
              type="primary"
              class="p-2"
              size="medium"
            >
              <table-column-filter
                :list="settingList"
                :default-setting="defaultSettings"
                v-model:settings="settings"
                domain="flycare"
              />
            </el-button>
          </div>
        </div>

        <el-table ref="customerData" height="600" :data="customerData">
          <!-- <el-table-column property="keyId" :label="$t('common.customer_id')" width="120" align="center" /> -->
          <el-table-column property="name" :label="$t('common.customer_name')" />
          <el-table-column label="OID">
            <template v-slot="scope">
              <div>
                <el-tooltip placement="top-start">
                  <template #content>
                    <div style="max-width: 300px; line-height: 160%">
                      <span>{{ scope.row.oid }}</span>
                    </div></template
                  >
                  <div>
                    {{ scope.row.oidSimple }}
                  </div>
                </el-tooltip>
              </div>
            </template>
          </el-table-column>
          <el-table-column property="oaId" :label="$t('common.oa_id')" />
          <el-table-column property="oaName" :label="$t('common.oa_name')" />

          <el-table-column
            v-if="showHeader('SHORT_NAME')"
            key="shortName"
            property="shortName"
            :label="$t('common.short_name')"
          />
          <el-table-column
            v-if="showHeader('ADDRESS')"
            key="address"
            property="address"
            :label="$t('common.address')"
          />
          <el-table-column
            v-if="showHeader('LINKMAN')"
            key="linkMan"
            property="linkMan"
            :label="$t('common.link_man')"
          />
          <el-table-column
            v-if="showHeader('MOBILE')"
            key="mobile"
            property="mobile"
            :label="$t('common.mobile')"
          />
          <el-table-column
            v-if="showHeader('EMAIL')"
            key="email"
            property="email"
            :label="$t('common.email')"
          />

          <el-table-column width="75px">
            <template v-slot="scope">
              <el-button
                v-model="radio"
                type="primary"
                text
                @click="confirmUserName(scope.row)"
                >{{ $t("common.confirm") }}</el-button
              >
              <!-- <el-radio v-model="radio" :label="scope.row.keyId" style="color: #fff;padding-left: 10px; margin-right: -25px;" @change.native="getCurrentRow(scope.row)" /> -->
            </template> </el-table-column
          >>
        </el-table>
      </el-card>
    </el-dialog>
    <!-- 修改日志状态 -->
    <el-dialog
      :title="$t('modules.report.edit_log')"
      v-model="editLogVisible"
      width="50%"
    >
      <el-form label-position="top">
        <el-form-item :label="$t('common.status') + ':'" prop="log">
          <el-radio v-model="radioStatus" label="0">{{
            $t("modules.report.log_status_list.dealt")
          }}</el-radio>
          <el-radio v-model="radioStatus" label="1">{{
            $t("modules.report.log_status_list.waiting")
          }}</el-radio>
          <el-radio v-model="radioStatus" label="2">{{
            $t("modules.report.log_status_list.ignore")
          }}</el-radio>
        </el-form-item>
        <el-form-item :label="$t('modules.report.remark') + ':'" prop="log">
          <el-input type="textarea" v-model="logForm.reason" />
        </el-form-item> </el-form
      ><template #footer>
        <span class="dialog-footer">
          <el-button text @click="editLogVisible = false">{{
            $t("common.cancel")
          }}</el-button>
          <el-button type="primary" @click="confirmEdit">{{
            $t("common.confirm")
          }}</el-button>
        </span></template
      >
    </el-dialog>
  </div>
</template>

<script>
import { getLog, editLog } from "@/api/report";
import { getUserKeyId } from "@/api/user";
import { toTime, toYMD, addDiver, toTenYMD } from "@/utils/index";
import TableColumnFilter from "@/components/page-setting/table-column-filter";

export default {
  components: {
    TableColumnFilter,
  },
  data() {
    return {
      settings: {
        conditions: [],
        columns: [],
      },
      logForm: {
        status: "",
        reason: "",
      },
      userData: {
        characterCode: "",
        keyId: "",
      },
      logId: undefined,
      radioStatus: "",
      editLogVisible: false,
      loading: false,
      nameLoading: false,
      userName: "",
      condition: "", // 客户名称搜索内容
      getUserNameVisible: false,
      totalCount: undefined,
      pageNo: 1,
      pageSize: 10,
      nameTotalCount: "",
      namePageNo: 1,
      namePageSize: 10,
      customerData: [],
      event: "",
      status: "",
      logList: "",
      selectTime: [],
      pickerOptions: {
        shortcuts: [
          {
            text: this.$t("common.last_month"),
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setMonth(start.getMonth() - 1);
              end.setMonth(end.getMonth() - 1);
              picker.$emit("pick", [start, end]);
            },
          },
          // {
          //   text: this.$t('common.current_month'),
          //   onClick(picker) {
          //     picker.$emit('pick', [new Date(), new Date()])
          //   }
          // },
          {
            text: this.$t("common.half_year"),
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setMonth(start.getMonth() - 6);
              picker.$emit("pick", [start, end]);
            },
          },
          {
            text: this.$t("common.one_year"),
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setMonth(start.getMonth() - 12);
              picker.$emit("pick", [start, end]);
            },
          },
        ],
      },
    };
  },
  computed: {
    eventTypeList() {
      return [
        {
          value: "REPORT_GENERATE_FAIL",
          label: this.$t("modules.report.event_type_list.rep_generate_fail"),
        },
        {
          value: "MAIL_NOTIFY_FAIL",
          label: this.$t("modules.report.event_type_list.mail_notify_fail"),
        },
        {
          value: "PLATFORM_DATA_LACK",
          label: this.$t("modules.report.event_type_list.platform_date_lack"),
        },
        {
          value: "CONTRACT_DATA_LACK",
          label: this.$t("modules.report.event_type_list.contract_data_lack"),
        },
      ];
    },
    logStatusList() {
      return [
        { value: 0, label: this.$t("modules.report.log_status_list.dealt") },
        { value: 1, label: this.$t("modules.report.log_status_list.waiting") },
        {
          value: 2,
          label: this.$t("modules.report.log_status_list.ignore"),
        },
      ];
    },
    settingList() {
      return {
        columns: [
          {
            title: this.$t("common.short_name"),
            code: "SHORT_NAME",
          },
          {
            title: this.$t("common.address"),
            code: "ADDRESS",
          },
          {
            title: this.$t("common.link_man"),
            code: "LINKMAN",
          },
          {
            title: this.$t("common.mobile"),
            code: "MOBILE",
          },
          {
            title: this.$t("common.email"),
            code: "EMAIL",
          },
        ],
      };
    },
    defaultSettings() {
      return {
        columns: [],
      };
    },
  },
  mounted() {
    this.getLogList();
  },
  activated() {
    this.getLogList();
  },
  methods: {
    showHeader(label) {
      // 重置高度
      // this.$nextTick(() => {
      //   this.$refs.customerData.doLayout()
      // })
      var list = this.settings["columns"];
      return list ? list.includes(label) : false;
    },
    showFormItem(label) {
      var list = this.settings["conditions"];
      return list ? list.includes(label) : false;
    },
    userNameDialogClose() {
      this.$refs.contractData.validateField("userName");
      this.condition = "";
    },
    getLogList() {
      let start, end;
      if (this.selectTime === null) {
        start = end = "";
      } else if (this.selectTime.length === 0) {
        start = end = "";
      } else {
        start = this.selectTime[0].toString();
        end = this.selectTime[1].toString();
      }
      let params = {
        characterCode: this.userData.characterCode,
        keyId: this.userData.keyId,
        startMonth: start,
        endMonth: end,
        reportEventType: this.event,
        status: this.status,
        pageNo: this.pageNo,
        pageSize: this.pageSize,
      };
      getLog(params)
        .then((res) => {
          this.totalCount = res.total;
          this.logList = res.list;
          for (let i = 0; i < this.logList.length; i++) {
            this.logList[i].creDate = toTenYMD(this.logList[i].creTime);
            this.logList[i].creTime = toTime(this.logList[i].creTime);
            this.logList[i].updTime = toTime(this.logList[i].updTime);
            this.logList[i].exceptionDescSimple =
              this.logList[i].exceptionDesc.substring(0, 15) + "...";
            if (this.logList[i].eventType === "REPORT_GENERATE_FAIL") {
              this.logList[i].eventTypeDes = 0;
            } else if (this.logList[i].eventType === "MAIL_NOTIFY_FAIL") {
              this.logList[i].eventTypeDes = 1;
            } else if (this.logList[i].eventType === "PLATFORM_DATA_LACK") {
              this.logList[i].eventTypeDes = 2;
            } else {
              this.logList[i].eventTypeDes = 3;
            }
          }
        })
        .catch((err) => {
          this.$message.error(err.message);
        });
    },
    //处理分页
    handleCurrentChange(val) {
      this.pageNo = val;
      this.getLogList();
    },
    //编辑状态
    editStatus(detail) {
      this.logId = detail.reportEventId;
      this.radioStatus = detail.status + "";
      this.logForm.reason = detail.dealRemark;
      this.editLogVisible = true;
    },
    ///确定修改日志内容
    confirmEdit() {
      let data = {
        dealRemark: this.logForm.reason,
      };
      editLog(this.logId, this.radioStatus, data)
        .then((res) => {
          this.getLogList();
        })
        .catch((err) => {
          this.$message.error(err.message);
        });
      this.editLogVisible = false;
      this.logForm.reason = "";
    },
    //处理用户姓名的分页
    handleNameCurrentChange(val) {
      this.namePageNo = val;
      this.getKeyId();
    },
    // 关闭Customer Name的对话框
    customerNameClose() {
      this.getUserNameVisible = false;
      this.condition = "";
    },
    // 清空Customer Name搜索框内容
    clearSearchName() {
      this.condition = "";
    },
    // 获取CharacterCode对应的keyId
    getKeyId(event) {
      this.nameLoading = true;
      this.$refs.name.blur();
      const params = {
        characterCode: "OPERATOR",
        pageSize: this.namePageSize,
        pageNo: this.namePageNo,
        condition: this.condition,
      };
      getUserKeyId(params)
        .then((res) => {
          this.nameTotalCount = res.total;
          this.customerData = res.list;
          for (let i = 0; i < this.customerData.length; i++) {
            this.customerData[i]["choose"] = false;
            if (this.customerData[i].oid != null) {
              let len = this.customerData[i].oid.length;
              let temp = this.customerData[i].oid + "";
              this.customerData[i].oidSimple =
                temp.substring(0, 8) + "..." + temp.substring(len - 8, len);
            }
          }
          // console.log(this.customerData)
          this.getUserNameVisible = true;
          this.nameLoading = false;
        })
        .catch((err) => {
          this.$message.error(err.message);
          this.nameLoading = false;
        });
    },
    // 确定获取的UserName
    confirmUserName(detail) {
      this.userData.characterCode = "OPERATOR";
      this.userData.keyId = detail.keyId;
      this.userName = detail.name;
      this.getUserNameVisible = false;
      this.condition = "";
    },
    // 取消获取的UserName
    cancelUserName() {
      this.getUserNameVisible = false;
      this.radio = "";
    },
    //清空Customer Name
    clearContractName() {
      this.userData.characterCode = "";
      this.userData.keyId = "";
    },
  },
};
</script>

<style scoped>
.box {
  margin: 0.2em 0.5em;
}
.title-logo {
  font-size: 0.8em;
  margin-left: 0px;
  color: #909399;
}
.box-header {
  font-weight: bold;
  font-size: 1.8em;
  color: #12263f;
}
.textLayout {
  display: flex;
  justify-content: center;
  align-items: center;
}
.el-dropdown-link {
  cursor: pointer;
  color: #409eff;
}
.el-icon-arrow-down {
  font-size: 12px;
}

.cell_gray {
  background-color: pink;
}

.tagBackground {
  color: black;
  background: rgba(255, 255, 255, 1);
  border-width: 0px;
}
</style>
